<?php

	set_time_limit(60*60);
	ini_set('memory_limit', '128M');

	class Directtracking {
		
		private $_configs;
		private $_date;
		private $_dbconn;
		
		public function __construct(){
			require_once "config.php";
			require_once dirname(__FILE__). '/util/connection.class.php';
			$this->_dbconn = Connection::getInstance();
			$this->_configs = require 'directtrack_config.php';
			$this->_date = date('Y-m-d', time() - 60*60*24);
		}
		
		public function saveDirectTrace2DB(){
			$campagins = $this->getActiveCampaigns();
		}
		
		public function getSubIDReport(){
			$version = '1_0';
			$affiliateId = 'CD1';
			$campaignId = '10024';
			$subids = 'subid1'; // Output: subid1, subid2, and subid4
			$date = '2012-04-11';
			
			$apiURL = "https://{$this->_configs['clientDomain']}/apifleet/rest/{$this->_configs['clientId']}/{$this->_configs['accessId']}/".
			    "statSubID/affiliate/{$affiliateId}/campaign/{$campaignId}/subid/{$subids}/{$date}";
			  
			$data = $this->getDirecttrackResponse($apiURL);
			var_dump($data);
		}
		
		
		/*
		 * get acitve campaign list
		 */
		private function getActiveCampaigns(){
			$apiURL = "https://{$this->_configs['clientDomain']}/apifleet/rest/{$this->_configs['clientId']}/"."{$this->_configs['accessId']}/campaign/active/";
			if ($campaignList = $this->getDirecttrackResponse($apiURL)) {
				foreach ($campaignList->resourceURL as $campaign){
					$attributes = $campaign->attributes();
					$campaignType = $attributes['metaData3'];
					$campaignId = (string) $attributes['metaData1'];
					$this->resolveCampaignInfos($campaignId, $campaignType);
				}
			}
		}
		
		/*
		 * Use campaign ID to get all cretives belong to this campaign
		 */
		private function resolveCampaignInfos($camId, $camType) {
			$apiURL = "https://{$this->_configs['clientDomain']}/apifleet/rest/{$this->_configs['clientId']}/"."{$this->_configs['accessId']}/creative/campaign/$camId/";
			
			if ($creativeList = $this->getDirecttrackResponse($apiURL)) {
				
				foreach ($creativeList->resourceURL as $creative) {
					$attributes = $creative->attributes();
					
					$creativeId = (string) $attributes['metaData1'];
					
					$this->getCreativeStat($creativeId, $camId, $camType);
				}
							
 			}			
		}
		
		/*
		 * Get statistics of a sepcified creative  
		 */
		private function getCreativeStat($creativeId, $camId, $camType) {
			$apiURL = "https://{$this->_configs['clientDomain']}/apifleet/rest/{$this->_configs['clientId']}/"."{$this->_configs['accessId']}/statCreative/affiliate/creative/$creativeId/{$this->_date}";
			
			if ($creativeStatsList = $this->getDirecttrackResponse($apiURL)) {
				foreach ($creativeStatsList->resource as $creativeStat) {
					$attributes = $creativeStat->attributes();
					$breakdownResourceURL = (string) $attributes['breakdownResourceURL'];
					$temp = explode('/', $breakdownResourceURL);
					$affiliateId = array_pop($temp);
					$addCode = $this->getAffiliateAddcode($affiliateId);
					$impression = (int) $creativeStat->impressions;
					$conversion = (int) $creativeStat->leads;
					$click = (int) $creativeStat->clicks;
					$revenue = (float) $creativeStat->revenue;
					if ($impression != 0 || $revenue != 0) {
						$this->saveAffiliatesRecord($camId, $addCode, 'Banner ' . $creativeId, $camType, $impression, $conversion, $click, abs($revenue));
					}
				}
			}
		}
		
		
		/*
		 * execute a request to direct track to retrive data
		 */
		private function getDirecttrackResponse($apiURL){
			$result = '';
			$headers[] = "Authorization: Basic ".base64_encode($this->_configs['username'].":".$this->_configs['password']);
			$headers[] = 'Cache-Control:No-Cache';			
			$ch = curl_init($apiURL);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($ch);
			preg_match('/\d\d\d/', $response, $status_code);
			if ($status_code[0] == '200') {
				$result =  simplexml_load_string($response);
			}
			curl_close($ch);
			return $result;
		}		
		
		/*
		 * get Affiliate addcode to save as pub
		 */
		private function getAffiliateAddcode ($affiliateId) {
			
			$apiURL = "https://{$this->_configs['clientDomain']}/apifleet/rest/{$this->_configs['clientId']}/affiliate/$affiliateId";
			
			if ($affiliate = $this->getDirecttrackResponse($apiURL)) {

				return (string) $affiliate->addCode;
			}
			
			return '';
			
		}
		
		/*
		 * traverse the publishers. if there's reporting about a campaign, get the campaign info, insert the campaign info and the reporting about
		 * this publisher related to this campaign into db
		 */
		private function saveAffiliatesRecord($cam, $pub, $cre, $buyType, $impressions, $conversions, $clicks, $spend){
			$time = date('YmdHis', strtotime($this->_date));
			
			$sql = "insert into site_data set cam=?, pub=?, pla='', cre=?, buy_type=?, impression=?, conversion=?, click=?, spend=?, time_new=?";
			try {
				$this->_dbconn->execute($sql, array($cam, $pub, $cre, $buyType, $impressions, $conversions, $clicks, $spend, $time));
			} catch (Exception $e)
			{
				QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
				throw new Model_Exception($e->getMessage(), $e->getCode());
			}
			
		}
		
	}
	
	$track = new Directtracking();
	if (!isset($argv[1])){
		$track->saveDirectTrace2DB();
	}else if(isset($argv[1]) && $argv[1] == 'subid'){
		$track->getSubIDReport();
	}
	
	
	